package it.hive.mediaplayer.listeners;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

public class MediaPlayerBufferListener implements ChangeListener<Duration> {
	private MediaPlayer player;

	private SimpleDoubleProperty bufferedProgress;
	private SimpleBooleanProperty onBuffer;

	public MediaPlayerBufferListener(MediaPlayer mediaPlayer) {
		player = mediaPlayer;
		player.bufferProgressTimeProperty().addListener(this);
		bufferedProgress = new SimpleDoubleProperty(-1);
		onBuffer = new SimpleBooleanProperty(false);
	}

	public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
		if (player != null) {
			double value = 1.0 * player.getBufferProgressTime().toMillis() / player.getTotalDuration().toMillis();
			if (value <= 1) {
				bufferedProgress.set(value);
				onBuffer.set(true);
			} else {
				if (onBuffer.get()) {
					bufferedProgress.set(value);
				}
				onBuffer.set(false);
			}
		}
	}

	public final SimpleDoubleProperty getBufferProgress() {
		return bufferedProgress;
	}

	public final SimpleBooleanProperty isOnBuffering() {
		return onBuffer;
	}

}
